package com.meirengu.webview.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.HttpUtil;
import com.meirengu.utils.MD5Util;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.model.KwPpdPush;
import com.meirengu.webview.model.KwPpdPushLog;
import com.meirengu.webview.service.KwPpdPushLogService;
import com.meirengu.webview.service.KwPpdPushService;
import com.meirengu.webview.utils.ConfigUtil;
import com.meirengu.webview.utils.PpdaiHttpUtil;
import com.meirengu.webview.utils.ppdai.Result;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * KwPpdPush服务实现层
 *
 * @author Mao
 * @create Mon May 07 20:08:35 CST 2018
 */
@Service
public class KwPpdPushServiceImpl extends BaseServiceImpl<KwPpdPush> implements KwPpdPushService {

    Logger logger = LoggerFactory.getLogger(KwPpdPushServiceImpl.class);

    @Autowired
    private KwPpdPushLogService kwPpdPushLogService;

    /**
     * @param
     * @return
     */

    public Integer applyLoan(String phone, String name, String idcard, String city) throws Exception {

        String url = ConfigUtil.getConfig("ppdai.url");
        String channel = ConfigUtil.getConfig("ppdai.channel");
        String source = ConfigUtil.getConfig("ppdai.source");
        String token = ConfigUtil.getConfig("ppdai.token");

        Map<String, String> params = new HashMap<>();
        params.put("ChannelId", channel);
        params.put("SourceId", source);
        params.put("token", token);
        String paramMd5Str = MD5Util.get32MD5("token=" + token + "&phone=" + phone);
        String sign = MD5Util.get32MD5("token=" + token + "&phone=" + phone + "&paramMd5=" + paramMd5Str);
        params.put("sign", sign);
        params.put("phone", phone);
        params.put("userName", name);
        params.put("shenfenzh", idcard);
        params.put("applyLoanAmount", "4000");
        params.put("applyLoanMonth", "7");
        params.put("daikuanyt", "消费分期");
        JSONObject json = new JSONObject();
        json.put("applyCity", city);
        params.put("info", json.toJSONString());


        //接口调用信息表
        KwPpdPush kwPpdPush = new KwPpdPush();
        kwPpdPush.setInterfaceCode("ppdai");
        kwPpdPush.setInterfaceName("拍拍贷");
        kwPpdPush.setMobile(phone);
        kwPpdPush.setCode(Constants.BUSINESS_STATUS_FAIL);


        KwPpdPushLog kwPpdPushLog = new KwPpdPushLog();
        kwPpdPushLog.setInterfaceCode("ppdai");
        kwPpdPushLog.setInterfaceName("拍拍贷");
        kwPpdPushLog.setMobile(phone);
        kwPpdPushLog.setSendUrl(url.toString());
        kwPpdPushLog.setParams(params.toString());

        HttpUtil.HttpResult hr = null;
        try {
            hr = HttpUtil.doPostForm(url, params);
            int code = hr.getStatusCode();
            if (code == 200) {
                kwPpdPushLog.setBackUrl(hr.toString());
                kwPpdPushLog.setHttpCode(200);
                kwPpdPushLog.setHttpContent(hr.toString());

                logger.info("==KwPpdPushServiceImpl.applyLoan request success. result:{}", hr.toString());
                String content = hr.getContent();
                JSONObject returnMsg = JSONObject.parseObject(content);
                String rCode = returnMsg.getString("Code");
                String rMsg = returnMsg.getString("Msg");
                if ("1".equals(rCode)) {
                    kwPpdPush.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                    kwPpdPush.setMessage("成功");
                    logger.info("==KwPpdPushServiceImpl.applyLoan business success");
                } else if (rMsg.contains("年龄")) {
                    kwPpdPush.setCode(Constants.BUSINESS_STATUS_BELIE);
                    kwPpdPush.setMessage("rCode: " + rCode + " rMsg:年龄不符合贷款发标要求");
                    logger.warn("==KwPpdPushServiceImpl.applyLoan business fail");
                } else {
                    kwPpdPush.setCode(Constants.BUSINESS_STATUS_OTHER);
                    kwPpdPush.setMessage("rCode: " + rCode + " rMsg:" + rMsg);
                    logger.warn("==KwPpdPushServiceImpl.applyLoan business fail");
                }
            } else {
                kwPpdPushLog.setBackUrl(hr.toString());
                kwPpdPushLog.setHttpCode(code);
                kwPpdPushLog.setHttpContent(hr.toString());
                logger.warn("==KwPpdPushServiceImpl.applyLoan request fail. code:{}, result:{}", code, hr.toString());
            }
        } catch (Exception e) {
            kwPpdPushLog.setHttpCode(408);
            kwPpdPushLog.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            insert(kwPpdPush);
            kwPpdPushLog.setPushId(kwPpdPush.getId());
            kwPpdPushLogService.insert(kwPpdPushLog);
            return kwPpdPush.getCode();
        }
    }


    /**
     * @param
     * @return
     */

    public Integer applyLoanBySleepingUser(String phone, String name, String idcard) throws Exception {


        //接口调用信息表
        KwPpdPush kwPpdPush = new KwPpdPush();
        kwPpdPush.setInterfaceCode("ppdsu");
        kwPpdPush.setInterfaceName("拍拍贷沉睡用户");
        kwPpdPush.setMobile(phone);
        kwPpdPush.setCode(Constants.BUSINESS_STATUS_FAIL);


        KwPpdPushLog kwPpdPushLog = new KwPpdPushLog();
        kwPpdPushLog.setInterfaceCode("ppdsu");
        kwPpdPushLog.setInterfaceName("拍拍贷沉睡用户");
        kwPpdPushLog.setMobile(phone);
        /*kwPpdPushLog.setSendUrl(url.toString());
        kwPpdPushLog.setParams(params.toString());*/

        try {

            //请求url
            String url = "https://openapi.ppdai.com/marketing/SDKSleepingUserService/IsSleepingUser";
            Result result = PpdaiHttpUtil.send(phone, name, idcard);
            boolean sucess = result.isSucess();
            if (sucess) {
                /*kwPpdPushLog.setBackUrl(hr.toString());*/
                kwPpdPushLog.setHttpCode(200);
                kwPpdPushLog.setHttpContent(result.getContext());

                logger.info("==KwPpdPushServiceImpl.applyLoanBySleepingUser request success. result:{}", result.getContext());
                String content = result.getContext();
                JSONObject returnMsg = JSONObject.parseObject(content);
                String scode = returnMsg.getString("Result");
                String smsg = returnMsg.getString("ResultMessage");
                String rcode = returnMsg.getString("ResultCode");
                String rMsg = returnMsg.getString("CodeMsg");
                if ("0".equals(scode)) {
                    JSONObject contentJson = returnMsg.getJSONObject("Content");
                    String status = contentJson.getString("Status");
                    if ("4".equals(status) || "5".equals(status)) {
                        kwPpdPush.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                        kwPpdPush.setMessage("成功");
                        logger.info("==KwPpdPushServiceImpl.applyLoanBySleepingUser business success");
                    } else {
                        kwPpdPush.setCode(Constants.BUSINESS_STATUS_OTHER);
                        kwPpdPush.setMessage("rCode: " + status + " rMsg:" + rMsg);
                        logger.warn("==KwPpdPushServiceImpl.applyLoanBySleepingUser business fail");
                    }
                } else {
                    kwPpdPush.setCode(Constants.BUSINESS_STATUS_OTHER);
                    kwPpdPush.setMessage("rCode: " + scode + " rMsg:" + rMsg + "  " + smsg);
                    logger.warn("==KwPpdPushServiceImpl.applyLoanBySleepingUser business fail");
                }
            } else {
                /*kwPpdPushLog.setBackUrl(hr.toString());*/
                kwPpdPushLog.setHttpCode(400);
                kwPpdPushLog.setHttpContent(result.getErrorMessage());
                logger.warn("==KwPpdPushServiceImpl.applyLoanBySleepingUser request fail. code:{}, result:{}", 400, result.getErrorMessage());
            }
        } catch (Exception e) {
            kwPpdPushLog.setHttpCode(408);
            kwPpdPushLog.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            insert(kwPpdPush);
            kwPpdPushLog.setPushId(kwPpdPush.getId());
            kwPpdPushLogService.insert(kwPpdPushLog);
            return kwPpdPush.getCode();
        }
    }

    /**
     * @param
     * @return
     */

    public Integer applyLoanBySleepingUser2(String phone, String name, String idcard) throws Exception {


        //接口调用信息表
        KwPpdPush kwPpdPush = new KwPpdPush();
        kwPpdPush.setInterfaceCode("ppdsu2");
        kwPpdPush.setInterfaceName("拍拍贷沉睡用户2");
        kwPpdPush.setMobile(phone);
        kwPpdPush.setCode(Constants.BUSINESS_STATUS_FAIL);


        KwPpdPushLog kwPpdPushLog = new KwPpdPushLog();
        kwPpdPushLog.setInterfaceCode("ppdsu2");
        kwPpdPushLog.setInterfaceName("拍拍贷沉睡用户2");
        kwPpdPushLog.setMobile(phone);
        /*kwPpdPushLog.setSendUrl(url.toString());
        kwPpdPushLog.setParams(params.toString());*/

        try {

            //请求url
            String url = "https://openapi.ppdai.com/marketing/SDKSleepingUserService/IsSleepingUser";
            Result result = PpdaiHttpUtil.send(phone, name, idcard);
            boolean sucess = result.isSucess();
            if (sucess) {
                /*kwPpdPushLog.setBackUrl(hr.toString());*/
                kwPpdPushLog.setHttpCode(200);
                kwPpdPushLog.setHttpContent(result.getContext());

                logger.info("==KwPpdPushServiceImpl.applyLoanBySleepingUser request success. result:{}", result.getContext());
                String content = result.getContext();
                JSONObject returnMsg = JSONObject.parseObject(content);
                String scode = returnMsg.getString("Result");
                String smsg = returnMsg.getString("ResultMessage");
                String rcode = returnMsg.getString("ResultCode");
                String rMsg = returnMsg.getString("CodeMsg");
                if ("0".equals(scode)) {
                    JSONObject contentJson = returnMsg.getJSONObject("Content");
                    String status = contentJson.getString("Status");
                    if ("4".equals(status) || "5".equals(status)) {
                        kwPpdPush.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                        kwPpdPush.setMessage("成功");
                        logger.info("==KwPpdPushServiceImpl.applyLoanBySleepingUser business success");
                    } else {
                        kwPpdPush.setCode(Constants.BUSINESS_STATUS_OTHER);
                        kwPpdPush.setMessage("rCode: " + status + " rMsg:" + rMsg);
                        logger.warn("==KwPpdPushServiceImpl.applyLoanBySleepingUser business fail");
                    }
                } else {
                    kwPpdPush.setCode(Constants.BUSINESS_STATUS_OTHER);
                    kwPpdPush.setMessage("rCode: " + scode + " rMsg:" + rMsg + "  " + smsg);
                    logger.warn("==KwPpdPushServiceImpl.applyLoanBySleepingUser business fail");
                }
            } else {
                /*kwPpdPushLog.setBackUrl(hr.toString());*/
                kwPpdPushLog.setHttpCode(400);
                kwPpdPushLog.setHttpContent(result.getErrorMessage());
                logger.warn("==KwPpdPushServiceImpl.applyLoanBySleepingUser request fail. code:{}, result:{}", 400, result.getErrorMessage());
            }
        } catch (Exception e) {
            kwPpdPushLog.setHttpCode(408);
            kwPpdPushLog.setHttpContent("Exception");
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        } finally {
            insert(kwPpdPush);
            kwPpdPushLog.setPushId(kwPpdPush.getId());
            kwPpdPushLogService.insert(kwPpdPushLog);
            return kwPpdPush.getCode();
        }
    }

    /*public void httpPost(String mobile, String name, String idNum) throws Exception{
        //应用id
        String appid = "53a9d9104df642ddac623c07c824ecee";
        String clientPrivateKey = "-----BEGIN PRIVATE KEY-----\n" +
                "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIHEg22aSOcPUyPi\n" +
                "VCqVXp6hw1Akyxkq6FKKH1+jSFPfiAWNaPc7Vfr2JVe1Heb5beazKOUSK8qq7RZg\n" +
                "NxIVOKG6CpvOnNSJwGBT2keU7ko0k9j/iSLocY+fyOTBUh9tvwZUgiePMcS1BnDC\n" +
                "Nu818FnfF5NcMrLEpsKiMeB+wjtpAgMBAAECgYA9+2YnSMU/kCNPBYDcIiJitLM8\n" +
                "qYZUzBjRq+WWYcBfR2qJ9GRJio7j4wQtI3ZX55Wl1rdWytod4IyD3osPWRGGADs4\n" +
                "xYXnSe+YKA6KqMPl9OjPCvV2MC3SoVksU5FORySb3TQOQhJx/CrmYqNZjpqt8DRl\n" +
                "InEbLT9w8pX1BhrR3QJBAPTcamWdtVArs2kboNt6qtL9gYNdaIFILkd7nLBsBdFm\n" +
                "WiT7hNdQh38s1rPhMBazDtpIdw0e5+YthvG8Up98LDMCQQCHq8B2zc0cERz1z+0B\n" +
                "N+ZkusaUIwRo6WNQgGXBNtHHTpjapVDxsYcFaXFAO1zBf/C7sZ4SlwN/69C6MSOf\n" +
                "E53zAkAYRyp9fM+XbV3SlBy05kq9tMj8n2xXNTLxf34ft/YztvRFKnMXbjKhF28K\n" +
                "Us+T0JkuZ3T2ZhQULHtuyH9gtM0lAkBSRg6GPVGYJqyYSMpiRcL67OVFqmKfOIFY\n" +
                "rTSH0jWvFvPNDBmlKFJILuRV3mnmki6rtA+3GEswBRJkBy6h5mSPAkEAuZkS0Rql\n" +
                "FrdCw4nJd6sZakXw/JOlKuOc/sQquod86up5mOFiUk8YrNoF2KR7UjdTiQTG+ZM5\n" +
                "PZR4ntTSiyrBhQ==\n" +
                "-----END PRIVATE KEY-----";

        String serverPublicKey = "-----BEGIN PUBLIC KEY-----\n" +
                "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCFZA2Q53gGaGuF1yzWUE7og2wC\n" +
                "xoV46EIACKbDu/M3Px2J8T6Er3NaYXKSLQdnDNqK3mv5f9BS/6G7WCBOnaUVTaQ7\n" +
                "RG7NvpLlH/+BL1J0vuc3LmQ/62p33CSX+s74b7kujlUPqe3dWmZ+08YDooe7Zm2E\n" +
                "hzKNdFGv7ZPwRR8PqQIDAQAB\n" +
                "-----END PUBLIC KEY-----";


        //初始化操作
        OpenApiClient.Init(appid, RsaCryptoHelper.PKCSType.PKCS8, serverPublicKey, clientPrivateKey);

        //请求url
        String url = "https://openapi.ppdai.com/marketing/SDKSleepingUserService/IsSleepingUser";
        Result result = OpenApiClient.send(url
                , new PropertyObject("Mobile", mobile, ValueTypeEnum.String)
                , new PropertyObject("Name", name, ValueTypeEnum.String)
                , new PropertyObject("IDNum", idNum, ValueTypeEnum.String));
        *//*System.out.println(String.format("返回结果:%s", result.isSucess() ? result.getContext() : result.getErrorMessage()));*//*
    }*/
}
